<script setup>
import { ref, nextTick, computed } from "vue";
import Form from "@/components/Form/index.vue";
import { ElMessage } from "element-plus";
import {
  queryDataPermissionList,
  operationDataPermission,
  deleteDataPermission,
} from "@/api/System";
import { useDistInfoStore } from "@/stores/dict.js";
import { getDistInfos, getDistInfo, hasGroupArea } from "@/api/Other";
import { useglobalStore } from "@/stores/global.js";
import { useRouter } from "vue-router";
import { flattenTree, buildTrees } from "@/utils/common.js";
const globalStore = useglobalStore();
const router = useRouter();
const distInfoStore = useDistInfoStore();
const modalRef = ref();
const formRef = ref();
const tableLoading = ref(false);
const modalTitle = ref("新增门店分组");
const messageBoxRef = ref();
const existAreaList = ref([]);
const btnLefts = ref([
  {
    label: "新增门店分组",
    plain: false,
    type: "primary",
    show: true,
    tips: "根据地理位置将所有门店进行分组。如，华东大区包含浙江，新增所有地理位置为浙江的门店，都属于华东大区分组",
    tipsStyle:
      "margin-left: 8px; color: #666666;text-align: center;font-size: 12px;font-style: normal;font-weight: 400;",
    img: new URL("@/assets/icon/btn-add.png", import.meta.url),
    click: async () => {
      openModal();
    },
  },
]);
const tableConfig = ref([
  {
    prop: "permissionId",
    label: "分组ID",
    width: "100",
  },
  {
    prop: "permissionName",
    label: "分组名称",
    width: "240",
  },
  {
    prop: "regionName",
    label: "包含地区",
    type: "slot",
    textOverflow: true,
    slotName: "regionName",
  },
  {
    prop: "storeCount",
    label: "门店数量",
    width: "90",
    type: "slot",
    slotName: "storeCount",
  },
  {
    prop: "lastUpdateTime",
    label: "最新更新",
    width: "240",
  },
  {
    type: "action",
    label: "操作",
    width: 170,
    btns: [
      {
        label: () => "编辑",
        type: "success",
        show: (row) => {
          return true;
        },
        click: async (row) => {
          delItem.value = row;
          openModal(row);
        },
      },
      {
        label: () => "删除",
        type: "danger",
        click: async (row) => {
          delItem.value = row;
          messageBoxRef.value.open();
        },
      },
    ],
  },
]);
const totalPage = ref(0);
const tableData = ref([]);

const handlerSearch = async (formInline) => {
  tableLoading.value = true;
  try {
    const { records, total } = await queryDataPermissionList({
      ...formInline,
      permissionType: 2,
    });
    totalPage.value = Number(total);
    tableData.value = records;
    tableLoading.value = false;
  } catch (e) {
    tableLoading.value = false;
  }
};
const toMapTree = (data) => {
  return data
    .filter((e) => e.area_code.substr(-2) == "00")
    .map((v) => ({
      label: v.area_name,
      value: v.id,
      children: v.children && toMapTree(v.children),
    }));
};

const formList = ref([
  {
    type: "input",
    key: "permissionName",
    label: "分组名称",
    width: "260px",
    clearable: true,
    maxlength: "20",
  },
  {
    type: "cascader",
    key: "address",
    label: "包含地区",
    width: "260px",
    clearable: true,
    options: [],
    props: { multiple: true },
  },
  {
    type: "textarea",
    key: "permissionRemark",
    label: "备注",
    width: "260px",
    minRows: 4,
    maxlength: "100",
    clearable: true,
  },
]);
const formRules = {
  permissionName: [
    { required: true, message: "请输入分组姓名", trigger: "change" },
  ],
  address: [{ required: true, message: "请选择包含地区", trigger: "change" }],
};
const closeModal = () => {
  modalRef.value.close();
};

const openModal = async(data = void 0) => {
  await getHas();
  modalRef.value.open(data);
  if (data) {
    getFormDetail(data);
  } else {
    delItem.value = null;
    modalTitle.value = "新增门店分组";
    const mapExistAreaList = existAreaList.value.cityIdList;
    setOptions(mapExistAreaList)
  }
};

const getFormDetail = (data) => {
  const mapExistAreaList = existAreaList.value.cityIdList.filter(v=>!data.cityIdList.includes(v));
  setOptions(mapExistAreaList)
  modalTitle.value = "编辑门店分组";
  const lists = [];
  data.provinceIdList.forEach((e) => {
    data.cityIdList.forEach((el) => {
      lists.push([e, el]);
    });
  });
  nextTick(() => {
    formRef.value.setForm({
      permissionName: data.permissionName,
      address: lists,
      permissionRemark: data.permissionRemark,
    });
  });
};
const modalLoading = ref(false);
const submitModal = async () => {
  try {
    modalLoading.value = true;
    const { state, data } = await formRef.value.submitForm();
    let provinceIdList = [];
    let cityIdList = [];
    let areaIdList = [];

    data.address.forEach((e) => {
      if (!provinceIdList.includes(e[0]) && e[0]) {
        provinceIdList.push(e[0]);
      }
      if (!cityIdList.includes(e[1]) && e[1]) {
        cityIdList.push(e[1]);
      }
      if (!areaIdList.includes(e[2]) && e[2]) {
        areaIdList.push(e[2]);
      }
    });

    const obj = JSON.parse(JSON.stringify(data));
    delete obj.address;
    if (state) {
      await operationDataPermission({
        ...obj,
        provinceIdList,
        cityIdList,
        areaIdList,
        permissionType: 2,
        id: delItem.value?.id,
      });
      closeModal();
      initSearch();
     
    } else {
      const messages = Object.values(data)[0];
      ElMessage({
        showClose: true,
        message: messages[0].message,
        type: "error",
      });
    }
  } finally {
    modalLoading.value = false;
  }
};
const delItem = ref();
const messageConfirm = async () => {
  await deleteDataPermission(delItem.value.id);
  ElMessage({
    showClose: true,
    message: "删除成功",
    type: "success",
  });
  initSearch();
};
const seachTableRef = ref();
const initSearch = async () => {
  seachTableRef.value.handlerSearch();
  const distInfo = await getDistInfo();
  const distInfos = await getDistInfos();
  distInfoStore.setDistInfo(distInfo);
  distInfoStore.setDistInfos(distInfos);
};
const toStorePage = (row) => {
  globalStore.setAllClear();
  globalStore.setStoreId(row.id);
  router.push({ name: "StoreManageIndex" });
};
const getHas = async () => {
  const res = await hasGroupArea();
  existAreaList.value = res;
};
// getHas();
const options = computed(() => {
  const areaInfo =
    sessionStorage.getItem("areaInfo") &&
    JSON.parse(sessionStorage.getItem("areaInfo"));
  return areaInfo;
});
const setOptions = (data) => {
  const filterList = flattenTree(options.value).map((s) => ({
    ...s,
    children: [],
  }));
  const tree = buildTrees(
    filterList.filter((i) => !data.includes(i.id))
  );
  formList.value[1].options = toMapTree(tree).filter((v) => v.children?.length);
};
defineExpose({ handlerSearch, initSearch });
</script>
<template>
  <div class="page-content">
    <SeachTable
      :tableType="1"
      ref="seachTableRef"
      :btnLefts="btnLefts"
      :tableLoading="tableLoading"
      :tableConfig="tableConfig"
      :tableData="tableData"
      :totalPage="totalPage"
      :showLine="false"
      @handlerSearch="handlerSearch"
    >
      <template #regionName="{ row }">
        {{ row.regionName.join(",") }}
      </template>
      <template #storeCount="{ row }">
        <span
          @click="toStorePage(row)"
          style="color: #3480ff; cursor: pointer"
          >{{ row.storeCount || 0 }}</span
        >
      </template>
    </SeachTable>
  </div>
  <Modal ref="modalRef" :title="modalTitle" :top="'35vh'" :width="'400px'">
    <template #content>
      <Form
        class="mt14"
        ref="formRef"
        :formList="formList"
        :formRules="formRules"
        labelWidth="80px"
      ></Form>
    </template>
    <template #footer>
      <div>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" :loading="modalLoading" @click="submitModal"
          >确定</el-button
        >
      </div>
    </template>
  </Modal>
  <MessageBox
    ref="messageBoxRef"
    :content="'确定删除该门店分组？'"
    :rightBtnTxt="'删除'"
    @confirm="messageConfirm"
  />
</template>

<style lang="less" scoped>
.mains {
}
</style>
